package com.github.tommas.admintpl.util;

import com.github.tommas.admintpl.security.AccountRealm;
import com.github.tommas.admintpl.security.permission.RestrictedPermission;
import com.github.tommas.admintpl.security.permission.restriction.AssertableRestriction;
import com.github.tommas.admintpl.security.permission.restriction.Restriction;
import org.apache.shiro.lang.util.Assert;
import org.apache.shiro.util.ThreadContext;

public class PermissionUtils {
    public static RestrictedPermission getAuthorizedPermission() {
        RestrictedPermission permission = (RestrictedPermission) ThreadContext.get(AccountRealm.AUTHORIZED_PERMISSION_KEY);
        Assert.notNull(permission);
        return permission;
    }

    @SuppressWarnings("unchecked")
    public static <T> void assertRestriction(Restriction restriction, T data) {
        if (restriction == null) {
            return;
        }

        if (!(restriction instanceof AssertableRestriction)) {
            throw new RuntimeException(String.format("Invalid assert restriction: %s", restriction.getName()));
        }

        ((AssertableRestriction<T>) restriction).assertRestriction(data);
    }
}
